package com.scmt.hmzd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scmt.core.common.exception.ScmtException;
import com.scmt.core.common.utils.ResultUtil;
import com.scmt.core.common.vo.Result;
import com.scmt.hmzd.config.WxConfig;
import com.scmt.hmzd.entity.HmTechnician;
import com.scmt.hmzd.entity.HmWxUser;
import com.scmt.hmzd.entity.LoginParam;
import com.scmt.hmzd.service.IHmTechnicianService;
import com.scmt.hmzd.service.IHmWxUserService;
import com.scmt.hmzd.wxLoginUtils.WxSecurityUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@Api(tags = "移动端后台接口")
@RestController
@RequestMapping("/scmt/appMain")
@Slf4j
public class WxLoginController {
    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private IHmWxUserService iHmWxUserService;

    @Autowired
    private IHmTechnicianService iHmTechnicianService;

    @Autowired
    private WxSecurityUtil securityUtil;


    @RequestMapping("/wxLogin")
    public Result<Object> wxLogin(@RequestBody LoginParam loginParam) throws WxErrorException {
        WxOAuth2AccessToken wxAccessToken = wxConfig.getWxMpService().getOAuth2Service().getAccessToken(loginParam.getCode());
        WxOAuth2UserInfo wxUserInfo = wxConfig.getWxMpService().getOAuth2Service().getUserInfo(wxAccessToken, null);
        if (wxUserInfo == null) {
            throw new ScmtException("用户信息获取异常，请刷新后再试！");
        }

        QueryWrapper<HmWxUser> hmWxUserQueryWrapper = new QueryWrapper<>();
        //需要确认哪个字段是唯一标识
        hmWxUserQueryWrapper.eq("openid", wxUserInfo.getOpenid());
        HmWxUser wxUserOld = iHmWxUserService.getOne(hmWxUserQueryWrapper);
        if (wxUserOld == null) {
            wxUserOld = new HmWxUser();
            wxUserOld.setNickname(wxUserInfo.getNickname());
            wxUserOld.setOpenid(wxUserInfo.getOpenid());
            wxUserOld.setHeadImgUrl(wxUserInfo.getHeadImgUrl());
            wxUserOld.setUnionId(wxUserInfo.getUnionId());
            wxUserOld.setCreateTime(new Date());
            iHmWxUserService.save(wxUserOld);
        } else {
            wxUserOld.setNickname(wxUserInfo.getNickname());
            wxUserOld.setOpenid(wxUserInfo.getOpenid());
            wxUserOld.setHeadImgUrl(wxUserInfo.getHeadImgUrl());
            wxUserOld.setUnionId(wxUserInfo.getUnionId());
            iHmWxUserService.updateById(wxUserOld);
        }
        //判断是否是技师
        QueryWrapper<HmTechnician> hmTechnicianQueryWrapper = new QueryWrapper<>();
        hmTechnicianQueryWrapper.lambda().eq(HmTechnician::getWxUserId, wxUserOld.getId());
        HmTechnician one = iHmTechnicianService.getOne(hmTechnicianQueryWrapper);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("isTechnician", 1);
        if (one != null) {
            hashMap.put("isTechnician", 2);
        }
        String accessToken = securityUtil.getWxUserToken(wxUserOld.getOpenid(), 1);
        hashMap.put("token", accessToken);
        return ResultUtil.data(hashMap);
    }



    @PostMapping("updateLocation")
    public Result<Object> updateLocation(@RequestBody LoginParam loginParam) {
        String wxUserId = securityUtil.getCurrentWxUser().getId();

        QueryWrapper<HmTechnician> hmTechnicianQueryWrapper = new QueryWrapper<>();
        hmTechnicianQueryWrapper.lambda().eq(HmTechnician::getWxUserId, wxUserId);
        hmTechnicianQueryWrapper.orderByDesc("last_login_time");
        hmTechnicianQueryWrapper.last("LIMIT 1");
        HmTechnician one = iHmTechnicianService.getOne(hmTechnicianQueryWrapper);
        if(one != null) {
            one.setLat(loginParam.getLat());
            one.setLng(loginParam.getLng());
            iHmTechnicianService.updateById(one);
        }
        return ResultUtil.data("位置信息更新成功");
    }


    @GetMapping("getUserInfo")
    public Result<Object> getUserInfo() {
        HmWxUser currentWxUser = securityUtil.getCurrentWxUser();
        //判断是否是技师
        QueryWrapper<HmTechnician> hmTechnicianQueryWrapper = new QueryWrapper<>();
        hmTechnicianQueryWrapper.lambda().eq(HmTechnician::getWxUserId, currentWxUser.getId());
        HmTechnician one = iHmTechnicianService.getOne(hmTechnicianQueryWrapper);
        currentWxUser.setIsTechnician(1);
        if (one != null) {
            currentWxUser.setIsTechnician(2);
            currentWxUser.setIsWork(one.getIsWork());
        }
        return ResultUtil.data(currentWxUser);
    }


//    @GetMapping("sendWxMsg")
//    public Result<Object> sendWxMsg() throws IOException {
//        Boolean result = wxConfig.sendWxgMessage("ohcjI5gOjJAhEyKN_C_rgadXg2QI", "1", "", "");
////        boolean result = wxConfig.sendRedpack("ohcjI5gOjJAhEyKN_C_rgadXg2QI", 1.0);
//        return ResultUtil.data(result);
//    }
}
